﻿#coding: utf-8

require 'sinatra/jsonp'

get '/thematics/' do
	res = []
	Thematic.all().each {|t| res << t}
	if params[:format] == 'js' then
		JSONP res.to_json
	else
		body(res.to_json)
		200
	end
end

get '/thematic/:id' do
	t = Thematic.get(params[:id])
	if t.nil? then
		404
	else
		res = t.to_json
		if params[:format] == 'js' then
			JSONP res
		else
			body(res)
			200
		end
	end
end

put '/thematic' do
	puts request.body.string
	begin
		data = JSON.parse(request.body.string)
	rescue JSON::ParserError
		400
	end
	if data.nil? or not data.has_key?('label') or not data.has_key?('url') then
		400
	else
		t = Thematic.create(
			:label => data['label'],
			:url => data['url']
		)
		t.save
		body(t.id.to_s)
		200
	end
end
